package com.tanhua.dubbo.api;

/**
 * @author lk
 * @date 2022-03-26
 */

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.domain.mongo.Movement;
import com.tanhua.model.domain.mongo.MovementTimeLine;
import com.tanhua.model.domain.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    TimeLineService timeLineService;

    //保存动态详情
    @Override
    public void publish(Movement movement) {
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            /*movement.setId(ObjectId.get());*/
       /* //查询当前用户的好友
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //循环好友数据，构建时间线数据存入数据库
        for (Friend friend : friends) {
            MovementTimeLine timeLine = new MovementTimeLine();
            //发表动态信息的id
            timeLine.setMovementId(movement.getId());
            //用户id
            timeLine.setUserId(friend.getUserId());
            //好友id
            timeLine.setFriendId(friend.getFriendId());
            //创建时间
            timeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(timeLine);
        }*/
            //调用工具类进行异步调用
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    //查询自己/好友动态功能
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = Query.query(criteria).skip((page - 1) * pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pageSize, 0, movements);
    }

    //获取好友动态
    @Override
    public List<Movement> findFriendMovements(Long userId, Integer page, Integer pageSize){
        Criteria criteria = Criteria.where("friendId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));
        //查询时间线表
        List<MovementTimeLine> lines = mongoTemplate.find(query, MovementTimeLine.class);
        //提取 动态id集合
        List<Object> movementIds = CollUtil.getFieldValues(lines, "movementId", Object.class);
        //根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(movementIds).and("state").is(1));
        return mongoTemplate.find(movementQuery, Movement.class);
    }

    //随机获取
    @Override
    public List<Movement> randomMovements(Integer pagesize) {
        //在Movement表中随机抽取 pageSize条数据
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(pagesize));
        //调用方法执行查询,需要传一个条件和封装类型
        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation, Movement.class);
        //调用方法返回动态数据
        return movements.getMappedResults();
    }


    //根据PID查询
    @Override
    public List<Movement> findByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    //查询动态详细信息
    @Override
    public Movement findMovement(ObjectId movementId){
        /*Query query =Query.query(Criteria.where("id").is(new ObjectId(movementId)));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);*/
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        return movement;
    }

    //获取动态
    @Override
    public PageResult findByMovement(Integer page, Integer pagesize, Long uid, Integer state) {
        Criteria criteria = new Criteria();
        if (uid!=null){
            criteria.and("userId").is(uid);
        }
        if (state!=null){
            criteria.and("state").is(state);
        }
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0,movements);
    }
}
